<?php

namespace asyncService\service;

use asyncService\message\interfaceMessage;

abstract class abstractService implements interfaceService{

    /**
     * 服务需要开启的进程数
     * @var float
     */
    protected $_process_number = 0.1;

    /**
     * 服务权重
     * @var int
     */
    protected $_weight = 1;

    /**
     * @var \asyncService\lib\log
     */
    protected $log = true;

    /**
     * @var interfaceMessage
     */
    protected $message;

    function __construct()
    {
        $this->setMessageTool(\asyncService\message\messageFactory::Produce());

        $this->ready();
    }

    public function ready(){
        if($this->log){
            $this->log = \asyncService\lib\log::getInstance(static::class);
        }
    }

    public function setMessageTool(interfaceMessage $message){
        $this->message = $message;
    }

    public function pop(){
        return  $this->message->pop(self::getServiceIdentifier());
    }

    public function push($value){
        return $this->message->push(self::getServiceIdentifier(),$value);
    }

    public function subscribe(){

        while($message = $this->pop()){
            try{

                $this->consume($message);

            }catch (\Exception $exception){

            }
        }
    }

    abstract function consume($message);


    public function restart(){
       return $this->message->sendSignal(self::getServiceRestartSignal());
    }

    public function tiggerRestart(){

    }

    public function tiggerStop(){

    }

    public function start()
    {
        if($this->log){
            $this->log->info(static::class." start !");
        }

        return true;
    }

    public function stop(){
        return $this->message->sendSignal(self::getServiceStopSignal());
    }

    public function __get($name)
    {
        $readOnly = "_".$name;
        if(isset($this->$readOnly)){
            return $this->$readOnly;
        }
    }

    static public function publish($value){
        return self::getInstance()->push($value);
    }

    static public function getServiceIdentifier(){

        return static::class;
    }

    static public function getServiceRestartSignal(){
        return self::getServiceIdentifier()."-restart";
    }

    static public function getServiceStopSignal(){
        return self::getServiceIdentifier()."-stop";
    }

    static function getInstance(){
        return new static();
    }
}